<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>图片大小测试</title>
  </head>
  <body>
    <div>
      <input type="file" id="file" />
      <button onclick="check()">显示</button>
      <div>
        <p>图片信息：<span id="info"></span></p>
        <p>width：<span id="pWidth"></span></p>
        <p>height：<span id="pHeight"></span></p>
        <p>size：<span id="pSize"></span></p>
      </div>
    </div>
    <script>
      var input = document.getElementById("file");
      var info = document.getElementById("info");
      var pWidth = document.getElementById("pWidth");
      var pHeight = document.getElementById("pHeight");
      var pSize = document.getElementById("pSize");
      function check() {
        if (input.files) {
          //读取图片数据
          var f = input.files[0];
          const infoStr = `name: ${f.name}, type: ${f.type}, size: ${f.size}`;
          info.innerHTML = infoStr;
          var reader = new FileReader();
          reader.onload = function (e) {
            var data = e.target.result;
            //加载图片获取图片真实宽度和高度
            var image = new Image();
            image.onload = function () {
              var width = image.width;
              var height = image.height;
              pWidth.innerHTML = width;
              pHeight.innerHTML = height;
              pSize.innerHTML = (f.size/1024/1024).toFixed(2) + 'M';
            };
            image.src = data;
          };
          reader.readAsDataURL(f);
        }
      }
    </script>
  </body>
</html>
